/**
 * 
 * @Author: biubiu0002
 * @Date: 2021-04-26 11:41
 **/
#include "Course.h"
#include "CourseMapper.h"
#include "list"
#include "iostream"
#include "fstream"
#include "sstream"
#include "string"
#include "vector"


using namespace std;

string CourseMapper::getNameByCourseId(string courseId){
    list<Course> courseList = getCourseList();
    for(Course course:courseList){
        if(course.getId()==courseId){
            return course.getName();
        }
    }
    return 0;
}

float CourseMapper::getCreditByCourseId(string courseId){
    list<Course> courseList = getCourseList();
    for(Course course:courseList){
        if(course.getId()==courseId){
            return course.getCredit();
        }
    }
    return 0;



}

list<Course> CourseMapper::loadCourseList(){
    list<Course> courseList;
    string line,field;
    ifstream ifs("../../resource/Course.txt",ios::in);
    if(!ifs){
        cout<<"Course.txt文件打开失败！"<<endl;
    }
    while(getline(ifs,line)){
        Course course;
        vector<string>infoList;
        istringstream iss(line);
        while(iss>>field){
            infoList.push_back(field);
        }
        course.setId(infoList[0]);
        course.setName(infoList[1]);
        course.setCredit(stof(infoList[2]));
        courseList.push_back(course);


    }
    ifs.close();
    return courseList;
}

int CourseMapper::batchInsertCourse(list<Course> &studentList) {
    ofstream ofs("../../resource/Course.txt",ios::out);
    if(!ofs){
        cout<<"Course.txt文件打开失败"<<endl;
    }
    for(Course stu:studentList){
        ofs<<stu.getId()<<" ";
        ofs<<stu.getName()<<" ";
        ofs<<stu.getCredit()<<endl;
    }
    return 0;
}

int CourseMapper::checkId(string courseId){
    list<Course> courseList = this->loadCourseList();
    for(Course course:courseList){
        if(course.getId()==courseId)
            return 1;
    }
    return 0;
}

const list<Course> &CourseMapper::getCourseList() const {
    return courseList;
}

void CourseMapper::setCourseList(const list<Course> &courseList) {
    CourseMapper::courseList = courseList;
}

CourseMapper::CourseMapper() {
    setCourseList(loadCourseList());
}
